import React, { useState, useEffect } from 'react';
import { NavBar, Tabs, Card, Tag, Button, Toast } from 'antd-mobile';
import { useNavigate, useSearchParams } from 'react-router-dom';
import axios from '../../axios';
import defaultProductImage from '../../assets/react.svg';
import './Com/Order.css';

// 商品信息接口
interface ProductInfo {
  _id: string;
  id: string;
  title: string;
  description: string;
  price: number;
  currentPrice: number;
  originalPrice: number;
  image: string;
  category: string;
  stock: number;
  sales: number;
  status: string;
  createdAt: string;
  updatedAt: string;
}

// 订单数据类型
interface Product {
  _id: string;
  productId: string;
  quantity: number;
}

interface Order {
  _id: string;
  id: string;
  userId: string;
  orderId: string;
  products: Product[];
  totalQuantity: number;
  status: string;
  orderTime: string;
  paymentMethod: string;
  deliveryAddress: string;
  caption: string;
  pickupCode?: string|null;
  completedTime?: string|null;
  refundReason?: string|null;
  refundAmount?: number|null;
  refundTime?: string|null;
  tradeNo?: string;
  paidTime?: string|null;
  outTradeNo?: string;
  createdAt: string;
  updatedAt: string;
}

const Order: React.FC = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const orderType = searchParams.get('type') || 'all';
  const [orders, setOrders] = useState<Order[]>([]);
  const [productInfoMap, setProductInfoMap] = useState<{ [key: string]: ProductInfo }>({});
  const [loading, setLoading] = useState(true);

  const handleBack = (): void => {
    navigate(-1);
  };

  // 英文参数到中文状态的映射
  const paramToStatusMap: { [key: string]: string } = {
    'unpaid': '待付款',
    'undelivered': '待发货',
    'pickup': '待提货',
    'uncommented': '待评价',
    'refund': '退款/售后'
  };

  // 获取商品信息
  const fetchProductInfo = async (productIds: string[]) => {
    try {
      const productInfoMap: { [key: string]: ProductInfo } = {};
      
      for (const productId of productIds) {
        try {
          const response = await axios.get(`http://localhost:3000/jjx/getproduct/${productId}`);
          if (response.data.code === 200 && response.data.data) {
            const productData = response.data.data;
            productInfoMap[productId] = productData;
          }
        } catch (error) {
          console.error(`获取商品信息失败 (${productId}):`, error);
        }
      }
      
      setProductInfoMap(productInfoMap);
    } catch (error) {
      console.error('获取商品信息失败:', error);
    }
  };

  // 获取订单数据
  const fetchOrders = async () => {
    try {
      setLoading(true);
      
      // 从 localStorage 获取用户ID
      const yonghuId = localStorage.getItem('yonghuId');
      
      if (!yonghuId) {
        console.error('未找到用户ID，请重新登录');
        setLoading(false);
        return;
      }
      
      // 调用后端API获取用户数据
      const response = await axios.get(`http://localhost:3000/hy/yonghu/${yonghuId}`);
      
      if (response.data.code === 200 && response.data.data) {
        const userData = response.data.data;
        const ordersData = userData.orders || [];
        setOrders(ordersData);
        console.log('获取到的订单数据:', ordersData);
        
        // 获取所有订单中的商品ID
        const allProductIds = ordersData.reduce((ids: string[], order: Order) => {
          order.products.forEach(product => {
            if (!ids.includes(product.productId)) {
              ids.push(product.productId);
            }
          });
          return ids;
        }, []);
        
        // 获取商品信息
        if (allProductIds.length > 0) {
          await fetchProductInfo(allProductIds);
        }
      } else {
        console.error('API返回错误:', response.data.message);
      }
    } catch (error) {
      console.error('获取订单数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchOrders();
  }, []);

  // 根据状态过滤订单
  const filterOrders = (status: string): Order[] => {
    let ordersToShow: Order[];
    if (status === 'all') {
      ordersToShow = orders;
    } else {
      const chineseStatus = paramToStatusMap[status];
      if (!chineseStatus) {
        ordersToShow = orders;
      } else if (status === 'refund') {
        ordersToShow = orders.filter(order =>
          order.status === '退款中' || order.status === '已退款' || order.status === '退款失败'
        );
      } else {
        ordersToShow = orders.filter(order => order.status === chineseStatus);
      }
    }
    // 按下单时间倒序排序
    return ordersToShow.sort((a, b) => new Date(b.orderTime).getTime() - new Date(a.orderTime).getTime());
  };

  // 格式化时间
  const formatTime = (timeString: string): string => {
    if (!timeString) return '-';
    
    const date = new Date(timeString);
    
    // 确保使用北京时间（UTC+8）
    const beijingTime = new Date(date.getTime() + (8 * 60 * 60 * 1000));
    
    const year = beijingTime.getUTCFullYear();
    const month = String(beijingTime.getUTCMonth() + 1).padStart(2, '0');
    const day = String(beijingTime.getUTCDate()).padStart(2, '0');
    const hours = String(beijingTime.getUTCHours()).padStart(2, '0');
    const minutes = String(beijingTime.getUTCMinutes()).padStart(2, '0');
    const seconds = String(beijingTime.getUTCSeconds()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  };

  // 获取状态标签颜色
  const getStatusColor = (status: string): string => {
    switch (status) {
      case '待付款':
        return '#ff4d4f';
      case '待发货':
        return '#faad14';
      case '待提货':
        return '#52c41a';
      case '待评价':
        return '#1890ff';
      case '退款中':
      case '已退款':
        return '#8c8c8c';
      default:
        return '#8c8c8c';
    }
  };

  // 获取状态文本（直接返回中文状态）
  const getStatusText = (status: string): string => {
    return status || '未知状态';
};

  // 获取订单操作按钮
  const getOrderActions = (order: Order) => {
    const actions = [];
    
    switch (order.status) {
      case '待付款':
        actions.push(
          <Button
            key="pay"
            size="small"
            color="primary"
            onClick={() => {
              // 计算订单总金额
              const totalAmount = order.products.reduce((total, product) => {
                const productInfo = productInfoMap[product.productId];
                const price = productInfo?.currentPrice || 0;
                return total + (price * product.quantity);
              }, 0);

              // 准备传递给支付页面的订单信息
              const paymentOrder = {
                orderId: order.orderId, //订单号
                products: order.products, //商品列表
                totalQuantity: order.totalQuantity, //总数量
                orderTime: order.orderTime, //订单时间
                totalAmount: totalAmount, //订单总金额
                deliveryAddress: order.deliveryAddress, //收货地址
                paymentMethod: order.paymentMethod //支付方式
              };

              // 调试信息
              console.log('Order页面传递给Payment的订单信息:', paymentOrder);

              // 跳转到支付页面
              navigate('/my/payment', { 
                state: { 
                  order: paymentOrder
                } 
              });
            }}
          >
            去付款
          </Button>
        );
        break;
      case '待发货':
        actions.push(
          <Button
            key="refund"
            size="small"
            style={{
              color: '#1677ff',
              background: 'transparent',
              border: 'none'
            }}
            onClick={() => {
              // 跳转到申请退款页面
              navigate('/my/refund-apply', {
                state: {
                  order: order
                }
              });
            }}
          >
            申请售后
          </Button>
        );
        break;
      case '待提货':
        // 添加申请退款按钮
        actions.push(
          <Button
            key="refund"
            size="small"
            style={{
              color: '#1677ff',
              background: 'transparent',
              border: 'none'
            }}
            onClick={() => {
              // 跳转到申请退款页面
              navigate('/my/refund-apply', {
                state: {
                  order: order
                }
              });
            }}
          >
            申请售后
          </Button>
        );
        actions.push(
          <Button
            key="pickup"
            size="small"
            color="primary"
            onClick={() => {
              // 跳转到提货码页面
              navigate('/my/ma', {
                state: {
                  pickupCode: order.pickupCode || 'PC' + Date.now()
                }
              });
            }}
          >
            查看提货码
          </Button>
        );
        actions.push(
          <Button
            key="confirm-pickup"
            size="small"
            color="success"
            onClick={async () => {
              try {
                const response = await axios.post('http://localhost:3000/hy/yonghu/update-order-status', {
                  orderId: order.orderId,
                  status: '待评价'
                });
                if (response.data.code === 200) {
                  setOrders(prevOrders => prevOrders.map(o =>
                    o.orderId === order.orderId ? { ...o, status: '待评价' } : o
                  ));
                } else {
                  Toast.show(response.data.message || '操作失败');
                }
              } catch {
                Toast.show('操作失败');
              }
            }}
          >
            我已提货
          </Button>
        );
        break;
      case '退款中':
        actions.push(
          <Button
            key="refund-progress"
            size="small"
            color="primary"
            onClick={() => {
              // 跳转到退款进度页面
              navigate('/my/refund-pending', {
                state: {
                  order: order
                }
              });
            }}
          >
            查看售后进度
          </Button>
        );
        break;
      case '已退款':
        actions.push(
          <Button
            key="refund-progress"
            size="small"
            color="primary"
            onClick={() => {
              // 跳转到退款进度页面
              navigate('/my/refund-success', {
                state: {
                  order: order
                }
              });
            }}
          >
            查看售后进度
          </Button>
        );
        break;
      case '退款失败':
        actions.push(
          <Button
            key="refund-progress"
            size="small"
            color="primary"
            onClick={() => {
              // 跳转到退款进度页面
              navigate('/my/refund-failed', {
                state: {
                  order: order
                }
              });
            }}
          >
            查看售后进度
          </Button>
        );
        break;
      case '待评价':
        actions.push(
          <Button
            key="evaluate"
            size="small"
            color="primary"
            onClick={() => {
              navigate('/my/remark', {
                state: {
                  order: order
                }
              });
            }}
          >
            去评价
          </Button>
        );
        break;
    }
    
    return actions;
  };

  const tabs = [
    { key: 'all', title: '全部' },
    { key: 'unpaid', title: '待付款' },
    { key: 'undelivered', title: '待发货' },
    { key: 'pickup', title: '待提货' },
    { key: 'uncommented', title: '待评价' },
    { key: 'refund', title: '退款/售后' }
  ];

  // 渲染订单列表
  const renderOrderList = (status: string) => {
    const filteredOrders = filterOrders(status);
    
    if (loading) {
      return <div className="loading">正在加载...</div>;
    }

    if (filteredOrders.length === 0) {
      const statusText = status === 'all' ? '订单' : (paramToStatusMap[status] || status);
      return (
        <div className="empty-state">
          <p>暂无{statusText}</p>
        </div>
      );
    }

    return (
      <div className="order-list">
        {filteredOrders.map(order => (
          <Card key={order.orderId} className="order-card">
            {/* 订单头部 */}
            <div className="order-header">
              <div className="order-header-left">
                <span className="order-id">订单号: {order.orderId}</span>
                <span className="order-time">{formatTime(order.orderTime)}</span>
              </div>
              <Tag color={getStatusColor(order.status)} className="order-status">
                {getStatusText(order.status)}
              </Tag>
            </div>
            
            {/* 商品信息 */}
            <div className="product-section">
              {order.products.map((product) => {
                const productInfo = productInfoMap[product.productId];
                return (
                  <div key={product._id} className="product-row">
                    <div className="product-row-content">
                      <div className="product-row-left">
                        <div className="product-image-small">
                          <img 
                            src={productInfo?.image || defaultProductImage} 
                            alt={productInfo?.title || `商品${product.productId}`} 
                            onError={(e) => {
                              console.error('图片加载失败:', e.currentTarget.src);
                              e.currentTarget.src = defaultProductImage;
                            }}
                          />
                        </div>
                        <div className="product-info">
                          <div className="product-name">
                            {productInfo?.title || `商品${product.productId}`}
                          </div>
                          <div className="product-price-row">
                            {productInfo?.currentPrice && (
                              <span className="price">¥{productInfo.currentPrice.toFixed(2)}</span>
                            )}
                            {productInfo?.originalPrice && productInfo.originalPrice > productInfo.currentPrice && (
                              <span className="original-price">¥{productInfo.originalPrice.toFixed(2)}</span>
                            )}
                            <span className="quantity">x{product.quantity}</span>
                          </div>
                        </div>
                      </div>
                      <div className="product-row-right">
                        <div className="product-total">
                          ¥{((productInfo?.currentPrice || 0) * product.quantity).toFixed(2)}
                        </div>
              </div>
                  </div>                   
                  </div>
                );
              })}
            </div>

            {/* 订单详情 */}
            <div className="order-info">
              {order.deliveryAddress && (
                <div className="info-item">
                  <span className="info-label">收货地址:</span>
                  <span className="info-value">{order.deliveryAddress}</span>
                </div>
              )}
              {order.pickupCode && (
                <div className="info-item">
                  <span className="info-label">提货码:</span>
                  <span className="info-value pickup-code">{order.pickupCode}</span>
                </div>
              )}
              {order.refundReason && (
                <div className="info-item">
                  <span className="info-label">退款原因:</span>
                  <span className="info-value">{order.refundReason}</span>
                </div>
              )}
            </div>

            {/* 订单底部 */}
            <div className="order-footer">
              <div className="order-total">
                <span className="total-label">实付款:</span>
                <span className="total-price">
                  ¥{order.products.reduce((total, product) => {
                    const productInfo = productInfoMap[product.productId];
                    const price = productInfo?.currentPrice || 0;
                    return total + (price * product.quantity);
                  }, 0).toFixed(2)}
                </span>
              </div>
              <div className="order-actions">
                {getOrderActions(order)}
              </div>
            </div>
          </Card>
        ))}
      </div>
    );
  };

  return (
    <div className="order-page">
      <NavBar onBack={handleBack}>
        我的订单
      </NavBar>
      
      <Tabs defaultActiveKey={orderType}>
        {tabs.map(tab => (
          <Tabs.Tab title={tab.title} key={tab.key}>
            {renderOrderList(tab.key)}
          </Tabs.Tab>
        ))}
      </Tabs>
    </div>
  );
};

export default Order;
